using MultiAgentsClient.ChatDataStructures;
using MultiAgentsClient.Service.WorkflowEngine;
using MultiAgentsShared;

namespace MultiAgentsClient.Manager.DataModel;

public class WorkflowDataModel
{
    private readonly Dictionary<int, BehaviorTreeConfig> WorkflowConfigCaches = [];

    public int selectWorkflow = 0;

    public List<WorkflowDisp> GetAllWorkflowDisps()
    {
        var returnList = new List<WorkflowDisp>();
        foreach (var wf in WorkflowConfigCaches.Values)
        {
            returnList.Add(wf.ToDisp());
        }
        return returnList;
    }

    public BehaviorTreeConfig? this[int workflowId]
    {
        get
        {
            if (WorkflowConfigCaches.ContainsKey(workflowId) == false)
            {
                return null;
            }

            return WorkflowConfigCaches[workflowId];
        }
    }

    public BehaviorTreeConfig GetWorkflow(string mentionedName)
    {
        return WorkflowConfigCaches
            .FirstOrDefault(wf => wf.Value.workflowType == BehaviorTreeConfig.WorkflowType.ManualTriggerWorkflow
                && wf.Value.name == mentionedName).Value;
    }

    public Dictionary<int, BehaviorTreeConfig> GetManualWorkflowConfigs()
    {
        return WorkflowConfigCaches
            .Where(wf => wf.Value.workflowType == BehaviorTreeConfig.WorkflowType.ManualTriggerWorkflow)
            .ToDictionary();
    }

    public void AddOrUpdateCahce(int workflowId, int ownerId, string Name, string workflowJson)
    {
        if (WorkflowConfigCaches.ContainsKey(workflowId) == false)
        {
            WorkflowConfigCaches.Add(workflowId, new BehaviorTreeConfig(workflowId, ownerId, Name, workflowJson));
        }
        else
        {
            WorkflowConfigCaches[workflowId].name = Name;
            WorkflowConfigCaches[workflowId].ownerId = ownerId;
            WorkflowConfigCaches[workflowId].configJson = workflowJson;
            WorkflowConfigCaches[workflowId].FromJson(workflowJson);
        }

    }

    public void UpdateAllJsonFromDb(List<Workflow> workflows)
    {
        WorkflowConfigCaches.Clear();

        foreach (Workflow workflow in workflows)
        {
            BehaviorTreeConfig workflowConfig = new(workflow.Id, workflow.OwnerId, workflow.Name, workflow.WorkflowJson);

            WorkflowConfigCaches.Add(workflow.Id, workflowConfig);
        }
    }

    public void RemoveWorkflowIfExist(int workflowId)
    {
        WorkflowConfigCaches.Remove(workflowId);
    }
}
